﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Migrator.Entities;
using Migrator.Services.Advertisement.Packets;

namespace Migrator.Services.MobileIPNodeService
{
    /// <summary>
    /// Manages solicitation requests
    /// </summary>
    public class Solicitor
    {
        public Solicitor(Node sender)
        {
            this.sender = sender;
        }

        public void Update()
        {
            timeLeft--;
        }

        /// <summary>
        /// Is it a good time to do a solicitation?
        /// i.e., has enough time passed since the last one?
        /// </summary>
        /// <returns></returns>
        public bool CanSolicitate()
        {
            return timeLeft <= 0;
        }


        /// <summary>
        /// Performs a solicitation
        /// </summary>
        /// <param name="sender">The node who sends the solicitation</param>
        public void Solicitate()
        {
            sender.Send(new ICMPRouterSolicitationPacket(sender));

            // Binary exponential backoff
            currentMaxInterval <<= 1;
            if (currentMaxInterval > MaxInterval)
                currentMaxInterval = MinInterval;

            // The next interval should be a randomized
            Random random = new Random();
            timeLeft = (int)random.Next(MinInterval, currentMaxInterval);
        }

        private Node sender;
        private int currentMaxInterval = MinInterval;
        private int timeLeft = MinInterval;

        #region Simulation parameters

        private const int MinInterval = 4;
        private const int MaxInterval = 64;

        #endregion
    }
}
